package result

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/pkg/errors"
	"go-gin-init/common/translator"
	"go-gin-init/common/xerr"
	"go.uber.org/zap"
	"net/http"
)

type JsonResult struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func JsonRsp(c *gin.Context, resp interface{}, err error) {

	if err == nil {
		c.JSON(http.StatusOK, &JsonResult{
			Code: xerr.SUCCESS,
			Msg:  "SUCCESS",
			Data: resp,
		})
	} else {
		Code := xerr.SERVER_COMMON_ERROR
		Msg := xerr.GetMsgByCode(Code)
		causeErr := errors.Cause(err)
		if e, ok := causeErr.(*xerr.CodeError); ok { //自定义错误类型
			//自定义CodeError
			Code = e.GetErrCode()
			Msg = e.GetErrMsg()
		}
		c.JSON(http.StatusOK, &JsonResult{
			Code: Code,
			Msg:  Msg,
			Data: nil,
		})
	}

}

func ParamErrorResult(c *gin.Context, err error) {
	// 获取validator.ValidationErrors类型的errors
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		// 非validator.ValidationErrors类型错误直接返回
		zap.L().Error("【http 请求参数格式错误】" + err.Error())
		JsonRsp(c, nil, xerr.NewErrCode(xerr.PARAM_FORMAT_ERROR))
		return
	}
	// validator.ValidationErrors类型错误则进行翻译
	// 并使用removeTopStruct函数去除字段名中的结构体名称标识
	c.JSON(http.StatusOK, gin.H{
		"code": xerr.PARAM_ERROR,
		"msg":  translator.RemoveTopStruct(errs.Translate(translator.Trans)),
	})
}
